/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.star.admin.controller;

import com.star.common.ActionType;
import com.star.common.CommonUtil;
import com.star.common.NewsCateData;
import com.star.common.RenderModel;
import com.star.common.UserRole;
import com.start.model.ActionModel;
import com.start.model.NewsCateModel;
import com.start.model.Re_Post_NewsCate_Model;
import com.start.model.SessionModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class AdminNewsCateController extends HttpServlet {
    private static final Logger logger = Logger.getLogger(AdminNewsCateController.class);
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }
    
    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminNewsCateController.handle:" + ex.getMessage(), ex);
        }
    }
    
    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/ajax-add-new-newscate":
                content = ajaxAddNewNewsCate(req, resp);
                break;
            case "/ajax-edit-newscate":
                content = ajaxEditNewsCate(req, resp);
                break;
            case "/ajax-delete-newscate":
                content = ajaxDeleteNewsCate(req, resp);
                break;
            case "/edit":
                content = renderEditPage(req, resp);
                break;     
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }
    
    
    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.NEWS_CATEGORY_VIEW) && !CommonUtil.checkAccess(req, UserRole.NEWS_CATEGORY_EDIT)) {
                resp.sendRedirect("/");
                return "";
            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "news_cate"));
            dic.setVariable("PAGE_TITLE", "Danh mục tin tức");

            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            List<NewsCateData> lstCate = newsCateModel.getCate(0, -1);
            if (lstCate != null && !lstCate.isEmpty()) {
                for (NewsCateData newsCateData : lstCate) {
                    TemplateDataDictionary section = dic.addSection("LIST_CATE");
                    section.setVariable("CATE_ID", String.valueOf(newsCateData.getId()));
                    section.setVariable("CATE_NAME", newsCateData.getName()); 
                }
            }
            
            List<NewsCateData> lstCateParent = newsCateModel.getCateParent(0, -1);
            if (lstCateParent != null && !lstCateParent.isEmpty()) {
                for (NewsCateData newsCateData : lstCateParent) {
                    TemplateDataDictionary section = dic.addSection("CATEPARENT_LIST");
                    section.setVariable("CATE_PA_ID", String.valueOf(newsCateData.getId()));
                    section.setVariable("CATE_PA_NAME", newsCateData.getName());
                }
            }

            if (CommonUtil.checkAccess(req, UserRole.NEWS_CATEGORY_EDIT)) {
                dic.showSection("CATEGORY_EDIT");
            }
            
            if(CommonUtil.checkAccess(req, UserRole.NEWS_CATEGORY_EDIT)){
                dic.showSection("ADD_PAGE");
            }
                        
            Template template = RenderModel.getAdminCTemplate("news_cate_page");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminNewsCateController.renderIndexPage: " + ex.getMessage(), ex);
        }
        return content;
    }
    
    
    
    private String renderEditPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);   
            if (!CommonUtil.checkAccess(req, UserRole.NEWS_CATEGORY_VIEW) && !CommonUtil.checkAccess(req, UserRole.NEWS_CATEGORY_EDIT)) {
                resp.sendRedirect("/");
                return "";
            }
                
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "news_cate"));
            dic.setVariable("PAGE_TITLE", "Danh mục tin tức");
                             
            if (CommonUtil.checkAccess(req, UserRole.NEWS_CATEGORY_EDIT)) {
                dic.showSection("CATEGORY_EDIT");
                dic.showSection("EDIT_PAGE");
            }            
                        
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.isEmpty()) {
                resp.sendRedirect("/newscate");
                return "";
            }       
                        
            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            NewsCateData newsCateData = newsCateModel.getNewsCateById(id);
            if (newsCateData != null) { 
                dic.setVariable("CATE_ID_EDIT", newsCateData.getId());
                dic.setVariable("CATE_NAME_EDIT", newsCateData.getName());
                dic.setVariable("CATE_CODE_EDIT", newsCateData.getCode());
                
                List<NewsCateData> lstCateParent = newsCateModel.getCateParent(0, -1);
                if (lstCateParent != null && !lstCateParent.isEmpty()) {
                    for (NewsCateData ob : lstCateParent) {
                        if(ob.getId().equals(id))
                            continue;
                        TemplateDataDictionary section = dic.addSection("CATEPARENT_LIST");
                        section.setVariable("CATE_PA_ID", String.valueOf(ob.getId()));
                        section.setVariable("CATE_PA_NAME", ob.getName());
                        if(ob.getId().equalsIgnoreCase(newsCateData.getId_cate_pa()))
                            section.showSection("CATE_SELECTED");
                    }
                }
                                 
                List<NewsCateData> lstCate = newsCateModel.getCate(0, -1);
                if (lstCate != null && !lstCate.isEmpty()) {
                    for (NewsCateData ob : lstCate) {
                        TemplateDataDictionary section = dic.addSection("LIST_CATE");
                        section.setVariable("CATE_ID", String.valueOf(ob.getId()));
                        section.setVariable("CATE_NAME", ob.getName()); 
                    }
                }  
                                      
                Template template = RenderModel.getAdminCTemplate("news_cate_page");
                content = template.renderToString(dic);
            } else {
                resp.sendRedirect("/newscate");
                return "";
            }
        } catch (Exception ex) {
            logger.error("AdminNewsCateController.renderEditPage: " + ex.getMessage(), ex);
        }
        return content;
    }
        
    
    private String ajaxAddNewNewsCate(HttpServletRequest req, HttpServletResponse resp) {
        String content;
        int error = 0;
        String msg = "Thêm danh mục tin tức thành công.";
        Map<String, String> data = new HashMap<>();
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
            if (!CommonUtil.checkAccess(req, UserRole.NEWS_CATEGORY_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }

            String name = req.getParameter("name") != null ? req.getParameter("name") : "";
            String code = req.getParameter("code") != null ? req.getParameter("code") : "";
            String idcate_Pa = req.getParameter("idcate_Pa") != null ? req.getParameter("idcate_Pa") : "";
            if (name.equalsIgnoreCase("")) {
                msg = "Tên danh mục không được trống.";
                error = -1;
            }
            if (code.equalsIgnoreCase("")) {
                msg = "Mã danh mục không được trống.";
                error = -1;
            }
            
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);
                NewsCateModel newsCateModel = NewsCateModel.getInstance();
                NewsCateData newsCateData = new NewsCateData(name, idcate_Pa, code);                
                String addCate = newsCateModel.addCate(newsCateData);
                if (addCate.equalsIgnoreCase("")) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.NEWS_CATEGORY_ADD, addCate, name);
                }
                data.put("id", String.valueOf(addCate));
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }
    
    
    
     private String ajaxEditNewsCate(HttpServletRequest req, HttpServletResponse resp) {
        int error = 0;
        String msg = "Chỉnh sửa danh mục tin tức thành công.";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
            if (!CommonUtil.checkAccess(req, UserRole.NEWS_CATEGORY_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }
            //String id = req.getParameter("pk") != null ? req.getParameter("pk") : "";
            String id = req.getParameter("idCate") != null ? req.getParameter("idCate") : "";
            //String name = req.getParameter("value") != null ? req.getParameter("value") : "";
            String name = req.getParameter("name") != null ? req.getParameter("name") : "";
            String code = req.getParameter("code") != null ? req.getParameter("code") : "";
            String idcate_Pa = req.getParameter("idcate_Pa") != null ? req.getParameter("idcate_Pa") : "";
            
            if (id.equalsIgnoreCase("")) {
                msg = "Id danh mục không được trống.";
                error = -1;
            }
            if (name.equalsIgnoreCase("")) {
                msg = "Tên danh mục tin tức không được trống.";
                error = -1;
            }
            if (code.equalsIgnoreCase("")) {
                msg = "Mã danh mục không được trống.";
                error = -1;
            }
            
            NewsCateModel newsCateModel = NewsCateModel.getInstance();
            if(!idcate_Pa.equals("")){
                List<NewsCateData> lstCateSub = newsCateModel.getCateSubByParent(id);
                if(lstCateSub != null && !lstCateSub.isEmpty()){
                    msg = name + " hiện đang là danh mục cha.";
                    error = -1;
                }
            }
            
            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);                
                NewsCateData newsCateEdit = newsCateModel.getNewsCateById(id);
                String newsCateName = newsCateEdit.getName();
                NewsCateData cateData = new NewsCateData(id, name, idcate_Pa, code);
                boolean editCate = newsCateModel.editCate(cateData);
                if (!editCate) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.NEWS_CATEGORY_EDIT, id, newsCateName);
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        return CommonUtil.toJSON(error, msg);
    }
     
          
    private String ajaxDeleteNewsCate(HttpServletRequest req, HttpServletResponse resp) {
        int error = 0;
        String msg = "Xoá danh mục tin tức thành công.";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
            if (!CommonUtil.checkAccess(req, UserRole.NEWS_CATEGORY_EDIT)) {
                return CommonUtil.toPermissionDenied();
            }

            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.equalsIgnoreCase("")) {
                msg = "Id danh mục không được trống.";
                error = -1;
            }

            if (error == 0) {
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);
                NewsCateModel newsCateModel = NewsCateModel.getInstance();
                NewsCateData newsCateData = newsCateModel.getNewsCateById(id);
                String name = newsCateData.getName();
                boolean deleteCate = newsCateModel.deleteCate(id);
                if (!deleteCate) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
                else{
                    //update cate sub
                    List<NewsCateData> lstCateSub = newsCateModel.getCateSubByParent(id);
                    if(lstCateSub != null && !lstCateSub.isEmpty()){
                        newsCateModel.editLstCate(lstCateSub);
                    }
                    
                    //delete record in re_news_newscate with idNewsCate = id
                    Re_Post_NewsCate_Model modelRe = Re_Post_NewsCate_Model.getInstance();
                    modelRe.deleteItemsByIdNewsCate(id);
                    
                    ActionModel actionModel = ActionModel.getInstance();
                    actionModel.addAction(req, userLogin, ActionType.NEWS_CATEGORY_DELETE, id, name);
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        return CommonUtil.toJSON(error, msg);
    } 
    
}
